package com.zxt.content.user.security.service;

import com.alibaba.fastjson.JSON;
import com.zxt.content.common.Bean.LoginUserInfoApiVO;
import com.zxt.content.common.utils.StringUtils;
import com.zxt.content.common.utils.UserUtil;
import com.zxt.content.user.constant.UserConstant;
import com.zxt.content.user.utils.RedisUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    public String createToken(LoginUserInfoApiVO user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        user.setToken(token);
        setUserAgent(user);
        //刷新Token保存进redis
        refreshToken(user);
        Map<String, Object> claims = new HashMap<>();
        claims.put(UserConstant.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 刷新令牌有效期
     *
     * @param user 登录信息
     */
    public void refreshToken(LoginUserInfoApiVO user) {
        user.setExpireTime(LocalDateTime.now().plusMinutes(UserUtil.EXPIRE_TIME));
        // 根据token将用户缓存
        String userKey = UserUtil.getToken(user.getToken());
        RedisUtils.set(userKey, JSON.toJSONString(user), TimeUnit.MINUTES, UserUtil.EXPIRE_TIME);
    }

    /**
     * 删除用户身份信息
     */
    public void deleteLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            RedisUtils.delete(UserUtil.getToken(token));
        }
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param user
     * @return 令牌
     */
    public void verifyToken(LoginUserInfoApiVO user) {
        LocalDateTime expireTime = user.getExpireTime();
        if (Objects.nonNull(expireTime)) {
            LocalDateTime time = LocalDateTime.now().plusMinutes(20);
            if (expireTime.isBefore(time)) {
                refreshToken(user);
            }
        }
    }

    /**
     * 设置用户代理信息
     *
     * @param user 登录信息
     */
    public void setUserAgent(LoginUserInfoApiVO user) {
        /*UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtil.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtil.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtil.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());*/
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, UserUtil.SECRET).compact();
    }

    public static void main(String[] args) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(UserConstant.LOGIN_USER_KEY, "9521b723aa5f430aab552019fae0969e");
        System.out.println(Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, "stbsaasmallbusiness").compact());
    }

}


